$(document).ready(function() {
	
	$(".alert-success[id='']").click(function(){
		$(this).toggle();
	})
	
	$(".alert-error").click(function(){
		$(this).toggle();
	})
	
	$("#alert-remove-success").click(function(){
		$(this).toggle();
	})
	
	$("#create-new").click(function(){
		$(this).hide();
		$("#form-new").show("fast");
		$(".alert-success").hide();
		$(".alert-error").hide();
		$("#form-search button[class='close']").trigger('click');		
	})
	
	$("#form-new button[class='close']").click(function(){
		$(this).parent().hide("fast");
		$("#create-new").show();
	})
	
	$("#search").click(function(){
		$(this).hide();
		$("#form-search").show("fast");
		$(".alert-success").hide();
		$(".alert-error").hide();
		$("#form-new button[class='close']").trigger('click');
	})
	
	$("#form-search button[class='close']").click(function(){
		$(this).parent().hide("fast");
		$("#search").show();
	})
	
	$("#submit-new").click(function(){
		$("#list").load(window.location.href+" #list > * ", getParams("#form-new"), function(resp,status){
			if (status == "error") {
				$(".alert-error").show();
			}else{
				$(".alert-success[id='']").show();
				$('#form-new')[0].reset();
			}
			$("#form-new button[class='close']").trigger('click');
	    });
		return false;
	})
	
	$("#submit-search").click(function(){
		$("#list").load($("#form-search").attr("action")+" #list > * ", getParams("#form-search"), function(resp,status){
			if (status == "error") {
				$(".alert-error").show();
			}
	    });
		return false;
	})
	
	$("#list").on("click", ".icon-trash", function() {
		var r=confirm("Vuoi veramente rimuovere questo elemento?");
		if (r==true){
			$("#list").load($(this).attr("href")+" #list > * ", function(resp,status){
				if (status == "error") {
					$(".alert-error").show();
				}else{
					$("#alert-remove-success").show();
				}
		    });
		}
		return false;
	});
	
});

function getParams(form){
	var param = {};
	$(form).find("input").each(function(){
		param[$(this).attr("name")] = $(this).val();
	});
	$(form).find("select").each(function(){
		param[$(this).attr("name")] = $(this).val();
	});
	$(form).find("textarea").each(function(){
		param[$(this).attr("name")] = $(this).val();
	});
	return param;
}